package com.webserver_v3.controller;

import com.webserver_v3.entity.User;
import com.webserver_v3.http.HttpServletRequest;
import com.webserver_v3.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;

public class UserController {
    private static File rootDir;
    private static File staticDir;
    private static File userDir;

    static {
        userDir = new File("./users");
        if (!userDir.exists()){
            userDir.mkdirs();
        }

        try {
            rootDir = new File(
                    UserController.class.getClassLoader()
                    .getResource(".").toURI()
            );
            staticDir = new File(rootDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    public void reg(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameters("username");
        String password = request.getParameters("password");
        String nickname = request.getParameters("nickname");
        String ageStr = request.getParameters("age");

        if ( username==null||username.isEmpty()||
            password==null||password.isEmpty()||
            nickname==null||nickname.isEmpty()||
            ageStr==null||ageStr.isEmpty()|| !ageStr.matches("[0-9]+")
        ){
            File file = new File(staticDir,"reg_info_error.html");
            response.setContentFile(file);
            return;
        }
        System.out.println(username+","+password+","+nickname+","+ageStr);
        int age = Integer.parseInt(ageStr);
        User user = new User(username,password,nickname,age);
        File file = new File(userDir,username+".obj");
        if (file.exists()){
            response.setContentFile(new File(staticDir,"have_user.html"));
            return;
        }

        try(
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                ) {

            oos.writeObject(user);
            response.setContentFile(new File(staticDir,"reg_success.html"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
